package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aries.ui.view.radius.RadiusRelativeLayout;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.event.CarCompareRecodeDeleteEvent;
import com.chexiehui.jc.mvp.car.CarModelCompareCovenant;
import com.chexiehui.jc.mvp.car.CarModelComparePresenter;
import com.chexiehui.jc.ui.fragment.TempFragment;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 车型对比
 */
public class CarModelCompareActivity extends BaseMvpActivity<CarModelComparePresenter> implements CarModelCompareCovenant.View {


    @BindView(R.id.rrl_add_model)
    RadiusRelativeLayout rrlAddModel;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.rtv_goto_compare)
    RadiusTextView rtvGotoCompare;
    private CommonAdapter<CarInfo> listAdapter;
    private BasePage<CarInfo> page;

    private List<String> selectedIds;

    private List<String> deleteIds;
    private int pageType; // 0 正常模式 1 删除模式

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("车型对比")
                .setRightText("编辑")
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        changePageType();
                    }
                });
    }

    private void changePageType(){
        if(pageType == 0){
            pageType = 1;
            titleBar.setRightText("取消");
            rtvGotoCompare.setEnabled(selectedIds.size() > 0);
            rtvGotoCompare.setText("删除");
        }else{
            pageType = 0;
            titleBar.setRightText("编辑");
            rtvGotoCompare.setEnabled(deleteIds.size() > 1);
            rtvGotoCompare.setText("开始比对");
        }
        listAdapter.notifyDataSetChanged();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_car_model_compare;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        selectedIds = new ArrayList<>();
        deleteIds = new ArrayList<>();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listAdapter.getDatas().size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });

        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        recycler.setAdapter(listAdapter = new CommonAdapter<CarInfo>(mContext, R.layout.item_car_model_compare_model, new ArrayList<>()) {
            @Override
            protected void convert(ViewHolder viewHolder, CarInfo item, int position) {
                if(pageType == 0){
                    viewHolder.setImageResource(R.id.iv_item_check, selectedIds.contains(item.getId()) ? R.mipmap.ic_check_s : R.mipmap.ic_check_us);
                }else{
                    viewHolder.setImageResource(R.id.iv_item_check, deleteIds.contains(item.getId()) ? R.mipmap.ic_check_s : R.mipmap.ic_check_us);
                }

                viewHolder.setText(R.id.tv_item_name, item.getSeriesName() + item.getName());
                viewHolder.setText(R.id.tv_item_price, "指导价：" + item.getNewPriceStrUnit());
            }
        });
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                changeChooseIds(listAdapter.getDatas().get(position).getId());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        rtvGotoCompare.setEnabled(selectedIds.size() > 1);
        mvpPresenter.getList(1);
    }

    private void changeChooseIds(String id) {
        if(pageType == 0){
            if(selectedIds.contains(id)){
                selectedIds.remove(id);
            }else{
                selectedIds.add(id);
            }
            listAdapter.notifyDataSetChanged();
            rtvGotoCompare.setEnabled(selectedIds.size() > 1);
        }else{
            if(deleteIds.contains(id)){
                deleteIds.remove(id);
            }else{
                deleteIds.add(id);
            }
            listAdapter.notifyDataSetChanged();
            rtvGotoCompare.setEnabled(deleteIds.size() > 0);
        }
    }

    @OnClick({R.id.rrl_add_model, R.id.rtv_goto_compare})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rrl_add_model:
                startActivityForResult(ChooseCarModelActivity.class, 20);
                break;
            case R.id.rtv_goto_compare:
                if(pageType == 0){
                    ArrayList<CarInfo> chooseList = new ArrayList<>();
                    for (int i = 0; i < listAdapter.getDatas().size(); i++) {
                        if(selectedIds.contains(listAdapter.getDatas().get(i).getId())){
                            chooseList.add(listAdapter.getDatas().get(i));
                        }
                    }
                    startActivity(CarBrandParameterActivity.class,
                            new BundleBuilder()
                                    .putSerializable("compareList", chooseList)
                                    .create());
                }else{
                    mvpPresenter.doDelete(deleteIds);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 20:
                if (resultCode == RESULT_OK) {
                    CarInfo carInfo = (CarInfo) data.getSerializableExtra("carInfo");
                    if (carInfo != null) {
                       listAdapter.getDatas().add(carInfo);
                        listAdapter.notifyDataSetChanged();
                    }
                }
                break;
        }
    }

    @Override
    protected CarModelComparePresenter createPresenter() {
        return new CarModelComparePresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<CarInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onDoDeleteSuccess(BaseModel<Object> successResult) {
        mvpPresenter.getList(1);
        EventBus.getDefault().post(new CarCompareRecodeDeleteEvent());
    }

    @Override
    public void onDoDeleteFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }
}
